package com.ldy.chat.service.impl;

import com.ldy.chat.service.ChatCliService;
import com.ldy.chat.service.ChatServerService;
import com.ldy.chat.service.Msg;
import com.ldy.chat.service.User;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;

import java.util.HashMap;

/**
 * @Auther lin DeYU
 * @Date 2021/3/30
 */
public class ChatServerServiceImpl implements ChatServerService.Iface {

    public static HashMap<String, String> userAddr=new HashMap<String, String>();


    @Override
    public String online(User user) throws TException {
        userAddr.put(user.name,user.address);
        return "上线成功 ! "+user.name;
    }

    @Override
    public String offine(User user) throws TException {
        userAddr.remove(user.name);
        return "下线成功 ! "+user.name ;
    }

    @Override
    public boolean forwardMsg(User user, Msg msg)  {
        TTransport tTransport= null;
        try {
            // 获取消息将要转发到的地址
            String addr = userAddr.get(user.name).trim();
            // 设置socket连接，定义数据传输的方式，数据传输通道是怎样的
            tTransport = new TFramedTransport(new TSocket(addr.split(":")[0],Integer.valueOf(addr.split(":")[1])));
            // 设置数据传输协议,就是传输什么样的数据，怎样进行序列化和反序列化
            TProtocol tProtocol = new TJSONProtocol(tTransport);
            ChatCliService.Client chatCliService=new ChatCliService.Client(tProtocol);
            // 开始数据传输通道
            tTransport.open();
            // 把消息转发给客户端,转发消息
            boolean b = chatCliService.acceptMag(user, msg);
            tTransport.close();
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if(tTransport!=null){
                tTransport.close();
            }
        }
        return false;
    }

}
